package com.baosight.sczx.zm.cg.service;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiColumn;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.soa.SoaManager;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.cd.Documents;
import com.baosight.sczx.zm.cg.domain.ZMCGNotice;


/**
 * 发送通知
 * <p>Title: ServiceZMCF15.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 严洪浩
 * @version 1.0
 * <pre>Histroy:
 *          2011-7-8 上午05:03:21  严洪浩  Create
 *</pre>
 */
public class ServiceZMCG11 extends ServiceEPBase {
	/**
	 * 初始化方法
	 * <p>Function: initLoad</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCF15</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-8上午05:14:44 严洪浩
	 * </p>
	 *
	 */
	@Override
	public EiInfo initLoad(EiInfo inInfo) {
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
		
		EiInfo outInfo = this.query(inInfo);
		
		outInfo.set("userId", UserSession.getUserId());
		outInfo.set("userName", UserSession.getInSessionProperty("UserCname"));
		outInfo.set("fdTime", StaticTools.getDateTime());
		outInfo.addBlock(getNameBlock());
		return outInfo;
	}
	
	
	
	
	protected EiBlock getNameBlock() {
		EiBlock block = new EiBlock("cmes.cx.phone");
		EiColumn EiColumn = new EiColumn("fdName");
		EiColumn.setType("C");
		block.addMeta(EiColumn);

		EiColumn = new EiColumn("fdMobile");
		EiColumn.setType("C");
		block.addMeta(EiColumn);

		List<Map> _list = new ArrayList<Map>();
		Map<String, String> _map = new HashMap<String, String>();
		_map.put("fdMobile", "");
		_map.put("fdName", "");
		_list.add(_map);

		List<Map> _listData = new ArrayList<Map>();
		try {
			_listData = dao.query("ZMCXPerson.queryforinterface", null);
		} catch (Exception e) {}
		
		for(int i = 0; i < _listData.size(); i++) {
			_list.add(_listData.get(i)); 
		} 
		block.setRows(_list);
		return block;
	}
	

	/**
	 * 查询方法
	 * <p>Function: query</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCF15</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-8上午05:14:50 严洪浩
	 * </p>
	 *
	 */
	@Override
	public EiInfo query(EiInfo inInfo) {
		if(inInfo.getBlock(EiConstant.queryBlock) == null){
			StaticTools.setQueryParameters(inInfo, "fdEndDate", StaticTools.getDate() + " 23:59:59", true);
		}
		else {
			String endTime = inInfo.getBlock(EiConstant.queryBlock).getCellStr(0, "fdEndDate");
			if(null != endTime && !"".equals(endTime)) {
				if(endTime.length() <= 10) {
					StaticTools.setQueryParameters(inInfo, "fdEndDate", endTime + " 23:59:59", true);
				}
			}
		}
		
		String fdPerson = UserSession.getInSessionProperty("UserCname") == null ? "" : UserSession.getInSessionProperty("UserCname").toString();//审批人
		StaticTools.setQueryParameters(inInfo, "fdPerson", fdPerson, true);//添加查询条件
		StaticTools.setQueryParameters(inInfo, "fdMiningId", UserSession.getInSessionProperty("miningCode"), true);
		EiInfo outInfo = super.query(inInfo, "ZMCGNotice.query1", new ZMCGNotice());
		outInfo.addBlock(getNameBlock());
		return outInfo;
	}
	
	/**
	 * 新增方法
	 * <p>Function: insert</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCF15</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-8上午05:15:01 严洪浩
	 * </p>
	 *
	 */
	@Override
	public EiInfo insert(EiInfo inInfo) {
		EiInfo out=new EiInfo(); 
		ZMCGNotice _dom = new ZMCGNotice();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		String fdStatus = "草拟";
		int i = 0;
		for (; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
	
			_dom.setFdKeyId(TablePk.getInstance().getNextValue("T_CG_NOTICE"));//主键
			_dom.setFdStatus(fdStatus);
			_dom.setFdPerson(UserSession.getInSessionProperty("UserCname").toString());
			_dom.setFdMiningId(UserSession.getInSessionProperty("miningCode").toString());	//矿井id
			_dom.setFdTime(StaticTools.getDateTime());
			this.dao.insert("ZMCGNotice.insert",_dom);
		}
		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out; 
	}

	/**
	 * 修改方法
	 * <p>Function: update</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCF15</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-8上午05:15:10 严洪浩
	 * </p>
	 *
	 */
	@Override
	public EiInfo update(EiInfo inInfo) {
		EiInfo out=new EiInfo(); 
		ZMCGNotice _dom = new ZMCGNotice();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		int i = 0;
		for (; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			if(validate(_dom)){
				_dom.setFdPerson(UserSession.getInSessionProperty("UserCname").toString());
				_dom.setFdTime(StaticTools.getDateTime());
				this.dao.update("ZMCGNotice.update",_dom);
			}
			else{
				out = this.query(inInfo);
				out.setStatus(-1);
				out.setMsg("只能修改草拟或者不通过的通知!"); 
				return out;
			}
		}
		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out;  
	}

	/**
	 * 删除方法
	 * <p>Function: delete</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCF15</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-8上午05:15:28 严洪浩
	 * </p>
	 *
	 */
	@Override
	public EiInfo delete(EiInfo inInfo) {
		EiInfo out=new EiInfo(); 
		ZMCGNotice _dom = new ZMCGNotice();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		int i = 0;
		for (; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			if(validate(_dom)){
				this.dao.delete("ZMCGNotice.delete", _dom);
			}
			else{
				out = this.query(inInfo);
				out.setStatus(-1);
				out.setMsg("只能删除草拟或者不通过的通知!"); 
				return out;
			}
		}
		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out;   	
	}
	
	/**
	 * 生效
	 * <p>Function: release</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-8-31上午07:24:30 严洪浩
	 * </p>
	 *
	 */
	public EiInfo release(EiInfo inInfo) {
		EiInfo out=new EiInfo(); 
		ZMCGNotice _dom = new ZMCGNotice();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		int i = 0;
		for (; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			if(validate(_dom)){
				String fdIsApproval = _dom.getFdIsApproval();//是否审批
				String fdStatus = fdIsApproval.equals("1") ? "待审批" : "已发布";
				_dom.setFdStatus(fdStatus);
				this.dao.update("ZMCGNotice.release",_dom);
			}
			else{
				out = this.query(inInfo);
				out.setStatus(-1);
				out.setMsg("只能生效草拟或者不通过的通知!"); 
				return out;
			}
			//发短信
			
			if(_dom.getFdMobile()!=null && !_dom.getFdMobile().trim().equals("")){
				sendMsg(_dom.getFdTitle(),_dom.getFdMobile());
			}
		}
		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out;  
	}
	   /**
		  * 向指定 URL 发送POST方法的请求
		  * 
		  * @param url
		  *            发送请求的 URL
		  * @param param
		  *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
		  * @return 所代表远程资源的响应结果
		  */
		 public static String sendPost(String url, String param) {
		 	System.out.println("请求的url:"+url);
		     PrintWriter out = null;
		     BufferedReader in = null;
		     String result = "";	
		     try {
		         URL realUrl = new URL(url);
		         // 打开和URL之间的连接
		         HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
		         // 设置通用的请求属性
		         conn.setConnectTimeout(3000);
		         conn.setReadTimeout(30000);
		         conn.setUseCaches(false);
		         // 发送POST请求必须设置如下两行
		         conn.setDoOutput(true);
		         conn.setDoInput(true);
		         conn.setRequestMethod("POST");
		         conn.setRequestProperty("accept", "*/*");
		         conn.setRequestProperty("connection", "Keep-Alive");
		         conn.setRequestProperty("user-agent",
		                 "Mozilla/5.0 (Windows; U; Windows NT 6.1;zh-CN;rv:1.9.2.6)");
		         // 获取URLConnection对象对应的输出流
		         out = new PrintWriter(conn.getOutputStream());
		         // 发送请求参数
		//         out.print(param);
		         // flush输出流的缓冲
		         out.flush();
		         // 定义BufferedReader输入流来读取URL的响应
		         in = new BufferedReader(
		                 new InputStreamReader(conn.getInputStream()));
		         String line;
		         while ((line = in.readLine()) != null) {
		             result += line;
		         }		      
		         System.out.println("短信测试发送结果："+result);
		     
		     } catch (Exception e) {
		    	
		         System.out.println("发送 POST 请求出现异常！"+e);		        
		         e.printStackTrace();
		         
		     }
		     //使用finally块来关闭输出流、输入流
		     finally{
		         try{
		             if(out!=null){
		                 out.close();
		             }
		             if(in!=null){
		                 in.close();
		             }
		         }
		         catch(IOException ex){
		             ex.printStackTrace();
		         }
		     }
		     return result;
		 } 
	private void sendMsg(String content,String fdMobile) {
		// TODO Auto-generated method stub
//		String url="http://api.ums86.com:8899/sms/Api/Send.do?";
		String url="http://api.ums86.com:8899/sms/Api/Send.do?";
		
		url+="SpCode=235186";       //企业编号
		url+="&LoginName=admin1";   //用户名称
		url+="&Password=cqnt@2015"; //用户密码
		String message = makeMessage(content);
		String info="";

	     try {
	    	
	    	 info= URLEncoder.encode(message, "gb2312");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		
		url+="&MessageContent="+info;//短信内容, 最大402个字或字符（短信内容要求的编码为gb2312或gbk）
		url+="&UserNumber="+fdMobile; //手机号码(多个号码用”,”分隔)，最多1000个号码
		String SerialNumber=StaticTools.getDocId(); //流水号，20位数字，每个请求流水号要求唯一
		int rand=(int)Math.random()*1000;
		SerialNumber+=rand;
		url+="&SerialNumber="+SerialNumber;
	//	url+="&ScheduleTime="; //预约发送时间
		url+="&f=1";    //提交时检测方式		
		 sendPost(url,"");
		
		
	}
	/**
	 * 根据短信模板生成短信
	 * 模板格式为“您收到一条标题为{xxxxxxxxxxxxxxxxxxxx}的调度通知，请登录ERP系统。在生产执行管理-调度通知中查看。”
	 * 将模板汇总的X换成需要发送的内容，一个X对应一个汉字或字符。数量必须一样多。
	 * @param content
	 * @return
	 */
	private String makeMessage(String content){
		String moban="您收到一条调度通知，内容：{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}。详情登录ERP查看。";
//        moban="您收到一封标题为{xxxxxxxxxxxxxxxxxxxx}的邮件，请登录协同办公系统处理。";
		String before=moban.substring(0,moban.indexOf("{"));
        String cont=moban.substring(moban.indexOf("{")+1,moban.indexOf("}"));
        String after=moban.substring(moban.indexOf("}")+1);
        int l=cont.length();
        if(content.length()>l){
        	content=content.substring(0,l);
        }
/*        else if(content.length()<l){
        	for(int i=1;i<=l-content.length();i++){
        		content+=" ";
        	}
        }*/
		return before+content+after;
	}

	/**
	 * 置顶
	 * <p>Function: delete</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCF15</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-8上午05:15:28 严洪浩
	 * </p>
	 *
	 */
	public EiInfo top(EiInfo inInfo) {
		EiInfo out=new EiInfo(); 
		ZMCGNotice _dom = new ZMCGNotice();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		int i = 0;
		for (; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			this.dao.update("ZMCGNotice.modifyTop",_dom);
		}
		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out; 
	}

	/**
	 * 取消置顶
	 * <p>Function: delete</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCF15</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-8上午05:15:28 严洪浩
	 * </p>
	 *
	 */
	public EiInfo cancelTop(EiInfo inInfo) {		
		EiInfo out=new EiInfo(); 
		ZMCGNotice _dom = new ZMCGNotice();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		int i = 0;
		for (; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			this.dao.delete("ZMCGNotice.modifyCancelTop",_dom);
		}
		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out; 
	}
	
	private boolean validate(ZMCGNotice _dom){
		String fdStatus = _dom.getFdStatus();
		if("草拟".equals(fdStatus) || "不通过".equals(fdStatus)){
			return true; 
		}
		else
			return false;
	}
	
	/**
	 * 查询附件
	 * <p>Function: queryFiles</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-6-30上午10:38:30 张志芳
	 * </p>
	 *
	 */
	public EiInfo queryFiles(EiInfo inInfo) {
		String keyId = inInfo.getString("fdKeyId");
		return Documents.getFilesInfo("filesresult", keyId);
	}
}
